<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        /*
            给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target，
            写一个函数搜索 nums 中的 target，
            如果目标值存在返回下标，否则返回 -1。
        */
        // 我的思路 
        // var search = function (nums, target) {
        //     for (let index = 0; index < nums.length; index++) {
        //         if (nums[index] == target) {
        //             return index;
        //         }
        //     }
        //     return -1;
        // }

        // 正儿八经的二分查找
        var search = function (nums, target) {
            let left = 0;
            let right = nums.length - 1;
            while (left <= right) {
                // let middle = parseInt(left + (right - left) / 2);
                let middle = (left + right) >>> 1;
                if (nums[middle] == target) {
                    return middle;
                } else if (nums[middle] > target) {
                    right = middle - 1;
                } else {
                    left = middle + 1;
                }
            }
            return -1;
        }
        console.log(search([-1, 0, 3, 5, 9, 12], 9));
        console.log(search([-1, 0, 3, 5, 9, 12], 2));
    </script>
</head>

<body>

</body>

</html>